import { createStore } from "vuex";

export default createStore({
  state: {
    list: [],
    error: false,
    loading: false,
    finished: false,
    refreshing: false,
  },
  mutations: {
    clearList(state) {
      state.list = [];
      state.refreshing = false;
    },
    addList(state, arr = []) {
      state.list.push(...arr);
    },
    setLoading(state, flag) {
      state.loading = flag;
    },
    setFinished(state, flag) {
      state.finished = flag;
    },
    setRefreshing(state, flag) {
      state.refreshing = flag;
    },
  },
  actions: {
    onLoad({ state, commit }) {
      setTimeout(() => {
        if (state.refreshing) {
          commit("clearList");
        }

        for (let i = 0; i < 10; i++) {
          commit("addList", [state.list.length + 1]);
        }

        commit("setLoading", false);

        if (state.list.length >= 40) {
          commit("setFinished", true);
        }
      }, 1000);
    },

    onRefresh({ commit, dispatch }) {
      commit("setFinished", false);

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      commit("setLoading", true);
      dispatch("onLoad");
    },
  },
});
